package com.exercise.ThreadSynchronization.volatileMethod;

public class Singleton {
    // 使用volatile防止指令重排序
    private static volatile Singleton instance;

    //私有构造函数
    private Singleton() {
    }

    public static Singleton getInstance() {
        //第一次检查
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        // 测试多线程环境下单例的正确性
        Runnable task = () -> {
            Singleton singleton = Singleton.getInstance();
            System.out.println(Thread.currentThread().getName() + ": " + singleton);
        };
        Thread t1 = new Thread(task, "Thread-1");
        Thread t2 = new Thread(task, "Thread-2");
        t1.start();
        t2.start();
    }


}
